package com.example.BluetoothTest;

//import java.io.IOException;
//import java.util.Vector;

import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
//import javax.microedition.lcdui.Alert;
//import javax.microedition.lcdui.Display;
//import java.text.Format;
//import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.lang.String;
//import java.text.DateFormat;
import java.util.TimerTask;

public class BTDeviceDiscovery extends TimerTask implements DiscoveryListener, Runnable{
	
	private BtInterfaceDisplay parent;
	 private static Object lock=new Object();
	protected Thread BtDiscoveryThread;
	private static java.util.Vector devices,services;
	//private Date currentTime;
    LocalDevice local;
    DiscoveryAgent agent;
	
	BTDeviceDiscovery(BtInterfaceDisplay parent) {
        this.parent = parent;

        // we have to initialize a system in different thread...
        BtDiscoveryThread = new Thread(this);
        BtDiscoveryThread.start();
    }
	
	public void run() {
		
		//this.parent.do_alert("Searching begin, please wait" , 4000);
		 try{
		        devices              = new java.util.Vector();
		        LocalDevice local    = LocalDevice.getLocalDevice();
		        DiscoveryAgent agent = local.getDiscoveryAgent();
		        agent.startInquiry(DiscoveryAgent.GIAC,this);
		        try {
		            synchronized(lock){
		                lock.wait();
		            }
		        }
		        catch (InterruptedException e) {
		            e.printStackTrace();
		        }
		    }catch(Exception e){this.parent.do_alert("Erron in initiating search" , 4000);}	
	}
	
	public void FindServices(RemoteDevice device){
		   /* try{
		        UUID[] uuids  = new UUID[1];
		        uuids[0]      = new UUID("27012f0c68af4fbf8dbe6bbaf7aa432a",false);    //The UUID of the ech service
		        local         = LocalDevice.getLocalDevice();
		        agent         = local.getDiscoveryAgent();
		        agent.searchServices(null,uuids,device,this);            
		    }catch(Exception e){this.do_alert("Erron in initiating search" , 4000);}*/
		}
		    
		public void deviceDiscovered(RemoteDevice remoteDevice,DeviceClass deviceClass) {
			if(!devices.contains(remoteDevice)){
			//this.parent.do_alert("Device found" , 4000);
		    devices.addElement(remoteDevice);
	    	Calendar cal = Calendar.getInstance();
	    	int TimeMonth = cal.get(Calendar.MONTH);
	    	int TimeDay = cal.get(Calendar.DAY_OF_MONTH);
	    	int TimeYear = cal.get(Calendar.YEAR);
	    	int TimeHour = cal.get(Calendar.HOUR);
	    	int TimeMinute = cal.get(Calendar.MINUTE);
	    	int TimeSecond = cal.get(Calendar.SECOND);
	    	String StrBtInf = new String("");
	    	String BtAddr = remoteDevice.getBluetoothAddress();
	    	//StrBtInf += "\n";
	    	StrBtInf += BtAddr.substring(8);
	    	//StrBtInf += cal.getTime().toString();
	    	StrBtInf += "  ";
	    	StrBtInf += String.valueOf(TimeMonth);
	    	StrBtInf += "/";
	    	StrBtInf += String.valueOf(TimeDay);
	    	StrBtInf += "/";
	    	StrBtInf += String.valueOf(TimeYear);
	    	StrBtInf += "-";
	    	StrBtInf += String.valueOf(TimeHour);
	    	StrBtInf += ":";
	    	StrBtInf += String.valueOf(TimeMinute);
	    	StrBtInf += ":";
	    	StrBtInf += String.valueOf(TimeSecond);
	    	StrBtInf += "\n";
	    	//StrBtInf += "\n";
	    	
		    //this.parent.getBtAddr(remoteDevice.getBluetoothAddress());
		    //this.parent.BtAddr = remoteDevice.getBluetoothAddress();
		    //Date currentTime = new Date();
		   // currentTime.getTime();
		    //SimpleDateFormat Timeformat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
		    //System.out.println("Today is " + Timeformat);
		    //String dateString = Timeformat.format(currentTime);
		    //this.parent.do_alert("timeformat good" , 4000);
		    //remoteDevice.getBluetoothAddress().concat("   ");
		    //String StrBtInf = remoteDevice.getBluetoothAddress();
		    //StrBtInf.concat("\n");
		    //StrBtInf.concat(CurrentTime);
		    this.parent.updateDeviceList(StrBtInf);
		    //this.parent.SearchedDevList.append(remoteDevice.getBluetoothAddress(), null);
		    }
		}

		public void servicesDiscovered(int transID,ServiceRecord[] serviceRecord) {
		   /* for (int x = 0; x < serviceRecord.length; x++ )
		        services.addElement(serviceRecord[x]);
		    try{
		        dev_list.append(((RemoteDevice)devices.elementAt(currentDevice)).
		                                            getFriendlyName(false),null);
		    }catch(Exception e){this.do_alert("Erron in initiating search" , 4000);}*/
		}
		public void inquiryCompleted(int param){
		    synchronized(lock){
		        lock.notify();
		    }
		    switch (param) {
		        case DiscoveryListener.INQUIRY_COMPLETED:    //Inquiry completed normally
		            if (devices.size() > 0){                 //Atleast one device has been found
		            	//this.parent.do_alert("device found in range",4000);
		                for (int i = 0; i <devices.size(); i++) {
		                    RemoteDevice remoteDevice=(RemoteDevice)devices.elementAt(i);}
		                //services = new java.util.Vector();
		                //this.FindServices((RemoteDevice)
		                         //devices.elementAt(0));     //Check if the first device offers the service
		            }else
		            	this.parent.do_alert("No device found in range",4000);
		        break;
		        case DiscoveryListener.INQUIRY_ERROR:       // Error during inquiry
		        	this.parent.do_alert("Inqury error" , 4000);
		        break;
		        case DiscoveryListener.INQUIRY_TERMINATED:  // Inquiry terminated by agent.cancelInquiry()
		        	this.parent.do_alert("Inqury Canceled" , 4000);
		        break;
		        default:
		        	//this.parent.do_alert("Unknown Response Code" , 4000);
		        break;
		       }
		}
		    
		public void serviceSearchCompleted(int transID, int respCode) {
		   /* switch(respCode) {
		        case DiscoveryListener.SERVICE_SEARCH_COMPLETED:
		            if(currentDevice == devices.size() -1){ //all devices have been searched
		                if(services.size() > 0){
		                    display.setCurrent(dev_list);
		                }else
		                    do_alert("The service was not found",4000);
		            }else{                               //search next device
		                currentDevice++;
		                this.FindServices((RemoteDevice)devices.elementAt(currentDevice));
		            }
		        break;
		        case DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
		             this.do_alert("Device not Reachable" , 4000);
		        break;
		        case DiscoveryListener.SERVICE_SEARCH_ERROR:
		             this.do_alert("Service serch error" , 4000);
		        break;
		        case DiscoveryListener.SERVICE_SEARCH_NO_RECORDS:
		            this.do_alert("No records returned" , 4000);
		        break;
		        case DiscoveryListener.SERVICE_SEARCH_TERMINATED:
		            this.do_alert("Inqury Cancled" , 4000);
		        break;
		     }*/
		}

}
